/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View.login;

import Controller.TiendaC;
import Controller.UsuarioC;
import Model.TiendaM;
import Model.UsuarioM;
import Util.AutoJComboBox;
import View.frmMenuPrincipal;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/**
 *
 * @author Maryluz
 */
public class frmInicioSesion extends javax.swing.JFrame {

    
    public static frmMenuPrincipal menu;
    int frmVentana;
    String[] listaTienda;
    ImageIcon icon ;
    String[][] oList;

    public frmInicioSesion(int ventana) {
        cargarTiendas();
        initComponents();
        frmVentana = ventana;
        icon = new ImageIcon(getClass().getResource("/Image/SysRealeza2.png"));
        this.setIconImage(icon.getImage()); 
        this.setLocationRelativeTo(null);
        this.setResizable(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel4 = new javax.swing.JPanel();
        txtUsuario = new javax.swing.JTextField();
        cbnUbicacion = new AutoJComboBox(listaTienda);
        jLabel4 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtContraseña = new javax.swing.JPasswordField();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        image = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setUndecorated(true);

        jPanel4.setBackground(new java.awt.Color(0, 0, 0));

        txtUsuario.setFont(new java.awt.Font("Calibri", 1, 16)); // NOI18N
        txtUsuario.setForeground(new java.awt.Color(0, 0, 102));
        txtUsuario.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtUsuarioFocusLost(evt);
            }
        });
        txtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtUsuarioKeyReleased(evt);
            }
        });

        cbnUbicacion.setFont(new java.awt.Font("Calibri", 1, 16)); // NOI18N
        cbnUbicacion.setForeground(new java.awt.Color(0, 0, 102));
        cbnUbicacion.setOpaque(false);
        cbnUbicacion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                cbnUbicacionKeyReleased(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Calibri", 1, 20)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(255, 255, 255));
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        jLabel4.setText("Ubicación ");

        jLabel2.setFont(new java.awt.Font("Calibri", 1, 20)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        jLabel2.setText("Usuario ");

        txtContraseña.setFont(new java.awt.Font("Calibri", 1, 16)); // NOI18N
        txtContraseña.setForeground(new java.awt.Color(0, 0, 102));
        txtContraseña.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtContraseñaKeyReleased(evt);
            }
        });

        btnAceptar.setFont(new java.awt.Font("Calibri", 1, 16)); // NOI18N
        btnAceptar.setForeground(new java.awt.Color(0, 0, 51));
        btnAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/OK.png"))); // NOI18N
        btnAceptar.setText("  ACEPTAR");
        btnAceptar.setToolTipText("");
        btnAceptar.setMaximumSize(new java.awt.Dimension(70, 70));
        btnAceptar.setMinimumSize(new java.awt.Dimension(70, 70));
        btnAceptar.setOpaque(false);
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnCancelar.setFont(new java.awt.Font("Calibri", 1, 16)); // NOI18N
        btnCancelar.setForeground(new java.awt.Color(0, 0, 51));
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/X.png"))); // NOI18N
        btnCancelar.setText("CANCELAR");
        btnCancelar.setToolTipText("");
        btnCancelar.setMaximumSize(new java.awt.Dimension(70, 70));
        btnCancelar.setMinimumSize(new java.awt.Dimension(70, 70));
        btnCancelar.setOpaque(false);
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Calibri", 1, 20)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        jLabel3.setText("Contraseña ");

        jLabel1.setFont(new java.awt.Font("Candara", 1, 24)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(251, 160, 105));
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/login.png"))); // NOI18N
        jLabel1.setToolTipText("");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cbnUbicacion, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtContraseña, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(18, 18, 18))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGap(32, 32, 32))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtContraseña, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(12, 12, 12)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbnUbicacion, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13))
        );

        image.setBackground(new java.awt.Color(0, 0, 0));
        image.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/logRealeza.png"))); // NOI18N
        image.setToolTipText("");
        image.setMaximumSize(new java.awt.Dimension(255, 245));
        image.setMinimumSize(new java.awt.Dimension(255, 245));
        image.setOpaque(true);
        image.setPreferredSize(new java.awt.Dimension(255, 245));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 583, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(image, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, 0)
                    .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 254, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(image, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(0, 0, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtUsuarioFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtUsuarioFocusLost
        UsuarioC oC = new UsuarioC();
        @SuppressWarnings("LocalVariableHidesMemberVariable")
        List<UsuarioM> oList = oC.listarUsuarios();

        for (int i = 0; i < oList.size(); i++) {
            if (oList.get(i).getCuenta() == null ? txtUsuario.getText().toUpperCase() == null : oList.get(i).getCuenta().equals(txtUsuario.getText().toUpperCase())) {
                cbnUbicacion.setSelectedItem(oList.get(i).getNomTienda());
            }
        }
    }//GEN-LAST:event_txtUsuarioFocusLost

    @SuppressWarnings("static-access")
    private void txtUsuarioKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsuarioKeyReleased

        if (evt.getKeyCode() == evt.VK_ENTER && !"".equals(txtUsuario.getText())) {
            UsuarioC oC = new UsuarioC();
            @SuppressWarnings("LocalVariableHidesMemberVariable")
            List<UsuarioM> oList = oC.listarUsuarios();

            for (int i = 0; i < oList.size(); i++) {
                if (oList.get(i).getCuenta() == null ? txtUsuario.getText().toUpperCase() == null : oList.get(i).getCuenta().equals(txtUsuario.getText().toUpperCase())) {
                    cbnUbicacion.setSelectedItem(oList.get(i).getNomTienda());
                }
            }
            txtContraseña.requestFocus();
        }
    }//GEN-LAST:event_txtUsuarioKeyReleased

    @SuppressWarnings("static-access")
    private void cbnUbicacionKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cbnUbicacionKeyReleased
        if (evt.getKeyCode() == evt.VK_ENTER) {
            btnAceptar.requestFocus();
        }
    }//GEN-LAST:event_cbnUbicacionKeyReleased

    @SuppressWarnings("static-access")
    private void txtContraseñaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtContraseñaKeyReleased
        if (evt.getKeyCode() == evt.VK_ENTER) {
            UsuarioC oC = new UsuarioC();
            @SuppressWarnings("LocalVariableHidesMemberVariable")
            List<UsuarioM> oList = oC.listarUsuarios();

            for (int i = 0; i < oList.size(); i++) {
                if (oList.get(i).getCuenta() == null ? txtUsuario.getText().toUpperCase() == null : oList.get(i).getCuenta().equals(txtUsuario.getText().toUpperCase())) {
                    cbnUbicacion.setSelectedItem(oList.get(i).getNomTienda());
                }
            }
            cbnUbicacion.requestFocus();
        }
    }//GEN-LAST:event_txtContraseñaKeyReleased

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        UsuarioC oC = new UsuarioC();
        @SuppressWarnings("LocalVariableHidesMemberVariable")
        List<UsuarioM> oList = oC.listarUsuarios();
        String password = new String(txtContraseña.getPassword());
        int error=0;
        for (int i = 0; i < oList.size(); i++) {

            if(i==0){
                error = ingresarLogin(i, oList, password);
            }else{
                if(error==0){
                    ingresarLogin(i, oList, password);
                    error=0;
                }else{
                    error = ingresarLogin(i, oList, password);
                }
            }}

            switch(error){
                case 1:
                JOptionPane.showMessageDialog(this, "Contraseña erronea.");
                txtContraseña.requestFocus();
                break;
                case 2:
                JOptionPane.showMessageDialog(this, "Nombre de usuario incorrecto.");
                txtUsuario.requestFocus();
                break;
                case 3:
                JOptionPane.showMessageDialog(this, "Seleccione ubicación de Tienda.");
                cbnUbicacion.requestFocus();
                break;
                case 4:
                JOptionPane.showMessageDialog(this, "Ingrese su contraseña.");
                txtContraseña.requestFocus();
                break;
                case 5:
                JOptionPane.showMessageDialog(this, "Ingrese su nombre de usuario.");
                txtUsuario.requestFocus();
                break;

            }
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        System.exit(0); 
    }//GEN-LAST:event_btnCancelarActionPerformed

  
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JComboBox cbnUbicacion;
    private javax.swing.JLabel image;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPasswordField txtContraseña;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
  private void cargarTiendas() {
        TiendaC oC = new TiendaC();
        List<TiendaM> oMs = oC.listarTiendas();
        @SuppressWarnings("LocalVariableHidesMemberVariable")
        String[] oList;
        if (oMs != null) {
            int size = oMs.size();
            oList = new String[size + 1];
            for (int a = 0; a < size; a++) {
                oList[0] = "----------------------";
                oList[a + 1] = oMs.get(a).getNomTienda();
            }
            listaTienda = oList;
        }
    }

    private int EncontrarIdTienda() {
        TiendaC oC = new TiendaC();
        List<TiendaM> oMs = oC.listarTiendas();
        if (oMs != null) {
            int size = oMs.size();
            oList = new String[size][2];
            for (int a = 0; a < size; a++) {
                oList[a][0] = oMs.get(a).getIdTienda() + "";
                oList[a][1] = oMs.get(a).getNomTienda();
            }

            for (int i = 0; i < size; i++) {
                for (int j = 0; j < 2; j++) {
                    if (cbnUbicacion.getSelectedItem().toString() == null ? oList[i][j] == null : cbnUbicacion.getSelectedItem().toString().equals(oList[i][j])) {
                        // System.out.println(Integer.parseInt(oList[i][0])+"") ;
                        return Integer.parseInt(oList[i][0]);
                    }
                }
            }

        }
        return -1;
    }

    private int ingresarLogin(int i, List<UsuarioM> oList, String password) {
                    if (!"".equals(txtUsuario.getText())) {
                if (!"".equals(password)) {

                    if (cbnUbicacion.getSelectedIndex() != 0) {

                        if (oList.get(i).getCuenta() != null && 
                                txtUsuario.getText().toUpperCase() != null && 
                                oList.get(i).getCuenta().equals(txtUsuario.getText().toUpperCase())) {
                            if (oList.get(i).getPass() == null ? password == null : oList.get(i).getPass().equals(password)) {
                                if (frmVentana == 1) {
                                    TiendaM oTiendaM = new TiendaM();
                                    oTiendaM.setIdUsuario(oList.get(i).getId());
                                    oTiendaM.setNomUsuario(oList.get(i).getCuenta());
                                    oTiendaM.setNombres(oList.get(i).getNomCompletos());
                                    oTiendaM.setNomTienda(cbnUbicacion.getSelectedItem().toString());
                                    this.dispose();
                                    
                                    menu=new frmMenuPrincipal(EncontrarIdTienda(), oTiendaM);
                                    menu.setVisible(true); 
                                    return 0;
                                }
                                this.dispose();
                            } else {
                                return 1;
                            }
                        } else {
                            return 2;
                        }
                    } else {
                        return 3;
                    }
                } else {
                    return 4;
                }
            } else {
                return 5;
                
            }
        return 0;
    }
}
